package cxt.com.recyclerview.demo2;

import android.content.Context;
import android.os.AsyncTask;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;

import com.daimajia.numberprogressbar.NumberProgressBar;

import java.util.List;

import cxt.com.recyclerview.R;

/**
 * 作者：chengxiangtong on 2017/1/9 17:37
 * 邮箱：528440900@qq.com
 */

public class DownLoadAdapter extends BaseAdapter {
    private List<Job> mData;
    private Context mContext;

    public DownLoadAdapter(Context mContext, List<Job> mData) {
        this.mContext = mContext;
        this.mData = mData;

    }

    @Override
    public int getCount() {
        return mData.size();
    }

    @Override
    public Object getItem(int position) {
        return mData.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        VH holder = null;
        final Job job = mData.get(position);
        if (convertView == null) {
            convertView = LayoutInflater.from(mContext).inflate(R.layout.item_download, parent, false);
            holder = new VH();
            holder.btn_download = (Button) convertView.findViewById(R.id.btn_download);
            holder.progressBar = (NumberProgressBar) convertView.findViewById(R.id.progress);
            convertView.setTag(holder);
        } else {
            holder = (VH) convertView.getTag();
        }

        holder.btn_download.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new DownloadTask(mContext, position).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, job.getUrl());
            }
        });
        if (job.progress == 100) {
            holder.btn_download.setText("完成");
        } else {
            holder.btn_download.setText("下载");
        }
        holder.progressBar.setProgress(job.getProgress());

        return convertView;
    }

    /**
     * 局部更新
     */
    public void notifyItemChanged(ListView listView, int position) {
        int fistPos = listView.getFirstVisiblePosition();
        int lastPos = listView.getLastVisiblePosition();
        Job job = mData.get(position);
        if (position >= fistPos && position <= lastPos) {
            View view = listView.getChildAt(position - fistPos);
            DownLoadAdapter.VH vh = (DownLoadAdapter.VH) view.getTag();
            vh.progressBar.setProgress(job.getProgress());
            if (job.progress == 100) {
                vh.btn_download.setText("完成");
            }
        }
    }


    class VH {
        Button btn_download;
        NumberProgressBar progressBar;
    }
}
